package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.NocvData;
import com.example.service.IndexService;
import com.example.vo.DataView;
import com.example.vo.NocvDataVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ChinaDataAdminController {


    @Autowired
    private IndexService indexService;

    /**
     * 模糊查询 带有分页
     * @return
     */
    @RequestMapping("/listDataByPage")
    public DataView listDataByPage(NocvDataVo nocvDataVo){
        //创建分页对象 当前页 每页限制大小
        IPage<NocvData> page=new Page<>(nocvDataVo.getPage(), nocvDataVo.getLimit());

        //创建模糊查询条件
        QueryWrapper<NocvData> queryWrapper=new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(nocvDataVo.getName()),"name",nocvDataVo.getName());
        //确诊多的排序上面
        queryWrapper.orderByDesc("value");
        //查询数据库
        indexService.page(page,queryWrapper);

        //返回数据封装
        DataView dataView=new DataView(page.getTotal(),page.getRecords());
        return dataView;
    }


    /**
     * 根据数据id删除
     * @param id
     * @return
     */
    @RequestMapping("/china/deleteById")
    public DataView deleteById(Integer id){
        indexService.removeById(id);
        DataView dataview=new DataView();
        dataview.setCode(200);
        dataview.setMsg("删除数据成功");
        return dataview;
    }

    /**
     * 新增或修改
     * 有id值是修改，没有就是新增
     * @param nocvData
     * @return
     */
    @RequestMapping("/china/addOrUpdateChina")
    public DataView addChina(NocvData nocvData){
        boolean save = indexService.saveOrUpdate(nocvData);
        DataView dataview=new DataView();
        if(save){
            dataview.setCode(200);
            dataview.setMsg("新增数据成功");
            return dataview;
        }
        dataview.setCode(100);
        dataview.setMsg("添加失败");
        return dataview;
    }


    /**
     *     Excel的拖拽或者点击上传
     *     1.前台页面发送一个请求，上传文件MutipartFile
     *     2.Controller接收文件参数是MutipartFile
     *     3.利用POI解析文件，把里面的数据一行一行解析出来
     *     4.每一条数据插入数据库
     * @return
     */
    @RequestMapping("/excelImport")
    public DataView excelImportChina(@RequestParam("file")MultipartFile file){

        DataView dataView = new DataView();
        if (file.isEmpty()) {
            dataView.setMsg("文件为空");
            return dataView;
        }
        try {

            //根据路径获取这个操作excel的实例
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            HSSFSheet sheet = wb.getSheetAt(0);

            //实体类集合
            List<NocvData> listData = new ArrayList<>();
            HSSFRow row = null;

            //循环sesheet页中数据从第二行开始，第一行是标题
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {

                //获取每一行数据
                row = sheet.getRow(i);
                NocvData data = new NocvData();
                data.setName(row.getCell(0).getStringCellValue());
                data.setValue(Integer.valueOf((int) row.getCell(1).getNumericCellValue()));
                listData.add(data);

            }

            //循环展示导入的数据，实际应用中应该校验并存入数据库
            indexService.saveBatch(listData);
            dataView.setCode(200);
            dataView.setMsg("导入成功");
            return dataView;
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataView.setCode(100);
        dataView.setMsg("导入失败");
        return dataView;
    }



    /**
     * 导出excel数据
     * @return
     * 查询数据库
     * 建立excel对象，封装数据
     * 建立输出流，输出文件
     */
    @RequestMapping("/outPortExcel")
    public void outPortExcel(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        List<NocvData> list = indexService.list();
        HSSFWorkbook wb = new HSSFWorkbook();
        //2-创建sheet页,设置sheet页的名字
        HSSFSheet sheet = wb.createSheet("中国数据表");
        //3-创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("城市名称");
        titleRow.createCell(1).setCellValue("确诊数量");
        //4-遍历将数据集合将数据放到对应的列中
        for (NocvData data : list){
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(data.getName());
            dataRow.createCell(1).setCellValue(data.getValue());
        }
        // 5.建立输出
        OutputStream os = null;

        try{
            //6-设置Excel的名称
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String("中国疫情数据表".getBytes(),"iso-8859-1") + ".xls");
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        }catch(Exception e){
            e.printStackTrace();

        } finally {
            try {
                if(os != null){
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
